public without sharing class SignatureController
{
    public Order__c aorder {get;set;}
    public WorkOrder__c worder {get;set;}
    public String signStr {get;set;}
    public String address {get;set;}
    public Boolean isError {get;set;}
    public Boolean isOrder {get;set;}
    public Case acase {get;set;}
    public String btn = '';
    public Boolean isSuccess {get;set;} 
    public String msg  {get;set;}
    public String caseId {get;set;}///
    public Set<String> rtSet;
    
    public SignatureController(ApexPages.StandardController con) 
    {
        Init(con.getRecord());
       
    }
    public void Init(SObject record){
          rtSet = new Set<String>();
                rtSet.add('TeachingTraining');
                rtSet.add('Reagents');
                rtSet.add('clinicalpromotion');
                rtSet.add('InstrumentsTraining');
                rtSet.add('calibration');
                rtSet.add('MaintenanceOrder');
                rtSet.add('ProblemSolving');
                
                //rtSet.add('InstallationOrder');

                rtSet.add('TechnicalTours');
                rtSet.add('ServiceOrder');
                rtSet.add('UsersReflect');
                rtSet.add('EvaluationTest');
                rtSet.add('SoftwareInstallationTraining');
        caseId = '';
        isError = false;
        if(record != null)
        {
            System.debug(record);
            isOrder = false;
            if(record instanceof Order__c)
            {
                aorder = (Order__c)record;
                List<Order__c> OrderList = [select Id, Name, Account__r.Name, CustomerSign__c, Signed__c
                                    from Order__c where Id =: aorder.Id];
                if(OrderList != null && !OrderList.isEmpty())
                {
                    if (OrderList[0].Signed__c)
                    {
                        isError = true;
                        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,Label.Err_CustomersSigned));
                    }
                    else
                    {
                        aorder = OrderList[0];
                    }
                    isOrder = true;
                }
                System.debug('*aorder: '+ aorder);
            }
            else if(record instanceof WorkOrder__c)
            {
                btn = ApexPages.currentPage().getParameters().get('btn');
                System.debug('@btn: '+btn);
           

                worder = (WorkOrder__c)record;

                List<WorkOrder__c> wList = [SELECT Id, CreatedById,Technician__c,Status__c,RecordType.DeveloperName , Account__r.Name, Case__c,Case__r.Engineer__c,Account__r.OwnerId
                , Signed_UsedDepartmen__c,Case__r.OwnerId,FullIn_Completed__c,DepartureTime__c,Install_Start_Datetime__c,ServiceTracking__c,
                    IMEINumber__c, IMEINumber_F__c,Case__r.RecordType.DeveloperName 
                                            FROM WorkOrder__c 
                                            WHERE Id =: worder.Id];
                if(wList != null)
                {   
                    try {
                        worder = wList[0];
                        acase = new Case();
                        acase.Id = worder.Case__c;
                        if(worder.Case__r.RecordType.DeveloperName == 'InstallationOrder' )caseId = worder.Id ;
                        //在是 InstallationOrder、MaintenanceOrder、ServiceOrder 提示 需勾选填写完毕不
                         Set<String> woset = new Set<String>{'ServiceOrder','InstallationOrder','NonAgentInstallationOrder','Relocation','MaintenanceOrder','CalibrationEngineer','Upgrade','ServiceOrder'};

                        if(!worder.FullIn_Completed__c && (
                            worder.Case__r.RecordType.DeveloperName == 'InstallationOrder'||
                            worder.Case__r.RecordType.DeveloperName == 'MaintenanceOrder'||
                            worder.Case__r.RecordType.DeveloperName == 'ServiceOrder'

                            || woset.contains(worder.RecordType.DeveloperName)) )throw new DmlException( '当前页面信息未填写完毕，请先勾选填写完毕!');
                        



                        if(!woset.contains(worder.RecordType.DeveloperName ) && 
                            
                            worder.Status__c != '处理中' ){

                            if(worder.Case__r.RecordType.DeveloperName == 'InstallationOrder' ){
                                caseId = worder.Id ;
                                 throw new DmlException( '当前页面信息未填写完毕，请补全信息后签名!');
                            }else{
                                 throw new DmlException( '工单状态不为处理中,不能签名!');

                            }
                        }
                        if((worder.RecordType.DeveloperName =='NonAgentInstallationOrder' ||
                            worder.RecordType.DeveloperName =='InstallationOrder' ||
                            worder.RecordType.DeveloperName =='ServiceOrder' || 
                            worder.RecordType.DeveloperName =='MaintenanceOrder' )

                            && (!rtSet.contains(worder.Case__r.RecordType.DeveloperName) && worder.Case__r.RecordType.DeveloperName != 'InstallationOrder' && worder.FullIn_Completed__c == false))throw new DmlException( Label.Err_NotFullInCompleted);

                        if(worder.DepartureTime__c == null ) throw new DmlException( '工程师出发时间为空,不能签名!');
                        if(worder.Install_Start_Datetime__c == null ) throw new DmlException( '服务开始时间为空,不能签名!');
                           
                        
                            
                        
                        /*
                         *   日期：2016-12-27
                         *   修改：刘文俊
                         *   目的：判断是否有权限签名
                         */
                        String lognUserID = UserInfo.getUserId();
                        //取出协同小组成员资料,并放到一个Map中保存，方便后面查询
                        Map<String,String> teamMap = new Map<String,String>() ;
                        List<WorkOrderTeam__c> teamList = [SELECT User__c,WorkOrder__c 
                                                           FROM WorkOrderTeam__c 
                                                           WHERE WorkOrder__c =: worder.Id];
                        for(WorkOrderTeam__c tm : teamList){
                            if(!teamMap.containsKey(tm.User__c)){
                                teamMap.put(tm.User__c, '');
                            }
                        }
                        System.debug('*** 协同小组成员: '+ teamMap);

                        //判断工程师是否有权限签名：可以签名条件
                        //1、使用科室负责人签名后才可签名
                        //2、工单创建者
                        //3、协同小组成员
                       /* if(btn.equals('EngineerSign')){
                            System.debug('*** 工程师_Sign: EngineerSign');
                            System.debug('*** 使用科室负责人是否签名: ' + worder.Signed_UsedDepartmen__c);
                            //使用科室负责人未签名，工程师不能签名
                            if(worder.Signed_UsedDepartmen__c == false){
                                isError = true;
                                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,Label.Err_NoSignedBeforeUsedDeptMan));
                                System.debug('*** 使用科室负责人未签名');
                            }
                            else{
                                System.debug('*** 工程师是否签名: ' + worder.Signed_Engineer__c);
                                if(worder.Signed_Engineer__c){//工程师已签名，不能再签名了
                                    System.debug('*** 工程师已签名，不能再签名了');
                                    isError = true;
                                    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,Label.Err_SignedByEngineer));
                                }
                                else if(!(worder.CreatedById == lognUserID || teamMap.containsKey(lognUserID))){
                                    System.debug('*** 没有权限。');
                                    isError = true;
                                    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,Label.Limit_Operate_Right));
                                }
                            }
                        }
                        else */
                        if(btn.equals('UserDepartmen') || btn.equals('ManageDepartment')){
                            //使用科室负责人已签名，不能再签名了
                            if(btn.equals('UserDepartmen') && worder.Signed_UsedDepartmen__c)throw new DmlException( Label.Err_SignedByUseDepartmen);
                            
                            //管理科室负责人已签名，不能再签名了
                            /*if(btn.equals('ManageDepartment') && worder.Signed_ManageDepartmen__c){
                                isError = true;
                                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,Label.Err_SignedByManageDepartmen));
                                return;
                            }
                            */
                            //取出个案指定的工程师的上级经理和协同小组成员的上级经理,并放到一个Map中保存，方便后面查询
                            Map<String,String> mgrMap = new Map<String,String>() ;
                            List<User> urlist = [SELECT ManagerId FROM User WHERE Id =: worder.Case__r.Engineer__c OR Id IN : teamMap.keySet()];
                            for(User u : urlist){
                                if(!mgrMap.containsKey(u.ManagerId)){
                                    mgrMap.put(u.ManagerId, '');
                                }
                            }
                            //判断使用科室负责人、管理科室负责人是否有权限签名：可以签名条件
                            //1、个案指定的工程师
                            //2、客户的Owner
                            //3、协同小组成员
                            //4、个案指定的工程师的上级经理和协同小组成员的上级经理
                            //5、个案的Owner
                            if(!(worder.Case__r.Engineer__c == lognUserID || 
                                worder.Case__r.OwnerId == lognUserID || 
                                worder.Account__r.OwnerId == lognUserID || 
                                worder.CreatedById == lognUserID ||
                                teamMap.containsKey(lognUserID) || 
                                mgrMap.containsKey(lognUserID))){
                               throw new DmlException( Label.Limit_Operate_Right);
                            }
                        }
                    }catch (Exception e) {
                        isError = true;
                        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,e.getMessage()));
                    }
                    
                    
                }
            }
        }
    }

    public void saveItem() {
        isSuccess  = true;
        msg = '';
        System.debug('*** signStr: ' + signStr);
            
            
            if(signStr != null && signStr != ''){
                    //<img alt="用户添加的图片" src="https://c.cs31.content.force.com/servlet/rtaImage?eid=a05p0000002S5xt&amp;feoid=00Np00000010c7U&amp;refid=0EMp0000000LYaH"></img>
                    //System.debug('*aorder.Account__r.Name:'+aorder.Account__r.Name);
                    Attachment at = new Attachment();
                    System.debug('***'+signStr);
                    at.Body = EncodingUtil.base64Decode(this.signStr.removeStart('data:image/png;base64,'));
                    at.ContentType = 'image/jpg';
                    System.debug('*at: '+ at);
                    if(isOrder){
                        at.ParentId = aorder.Id;
                        at.Name = aorder.Account__r.Name + '_Sign.jpg';
                        try {
                            List<Attachment> atts = [select Id from Attachment where ParentId = :aorder.Id and Name = :(aorder.Account__r.Name + '_Sign')];
                            if (atts.size() > 0)
                            {
                                delete atts;
                            }
                            insert at;
                            //aorder.Signed__c = true;
                            //aorder.CustomerSign__c = EncodingUtil.base64Decode(this.signStr.removeStart('data:image/png;base64,'));
                            aorder.CustomerSign__c = '<img src="/servlet/servlet.FileDownload?file=' + at.Id + '"/>';
                            //aorder.SignUrl__c = '/servlet/servlet.FileDownload?file=' + at.Id;
                            aorder.Receive_Goods_Date__c = Date.today();

                            update aorder;
                        } catch (Exception ex) {
                            isSuccess = false;

                            ApexPages.addMessages(ex);
                           //  return null;
                        }
                    }
                    else{
                        system.debug(worder.CreatedById+'=====================');
                       
                        /*
                         *   日期：2016-12-28
                         *   修改：刘文俊
                         *   目的：修改工单完成状态的逻辑
                         *   描述：工单对象上增加了三个字段:Signed_Engineer__c | Signed_ManageDepartmen__c | Signed_UsedDepartmen__c
                         *         用来记录是否签名，代替使用附件数量来判断是否签名
                         */
                        //如果附件保存成功，则设置各个签名标示字段值
                        System.debug('*** 签名角色：' + btn);
                       /* if(btn.equals('EngineerSign')){
                            System.debug('*** 工程师签名了！' );
                            worder.Signed_Engineer__c = true ;
                        }
                        else if(btn.equals('ManageDepartment')){
                            System.debug('*** 管理科室签名了！' );
                            worder.Signed_ManageDepartmen__c = true ;
                        }
                        else*/
                        if(btn.equals('UserDepartmen')){
                            System.debug('*** 使用科室签名了！' );
                            worder.Signed_UsedDepartmen__c = true ;
                        }
             
                        //如果工程师和使用科室负责人都已签名
                        //1、设置工单状态--->完成
                        //2、设置工单安装完成时间--->now()
                        //3、设置个案状态--->完成

                        /*
                        *   20180418 
                        */
                        //保养和服务工单 客户签名为完成节点 工单-->完成 个案--->关闭

                        //安装工单  客户签名 获取服务完成时间  工单-->完成  个案 ---> 不关 确认上传附件:检测是否包含安装报告 关闭个案

                        //经销商:不显示工程师签名  迈克:显示工单的创建人

                        //取消 工程师签名
                         Set<String> woset = new Set<String>{'InstallationOrder','NonAgentInstallationOrder','Relocation','MaintenanceOrder','CalibrationEngineer','Upgrade','ServiceOrder'};

                        System.debug(worder.Case__r.RecordType.DeveloperName);
                        System.debug(rtSet);
                        worder.ServiceSignTime__c = System.now();
                        worder.ServiceSignAddress__c = address;
                        if( worder.IMEINumber_F__c != null )acase.IMEINumber__c = worder.IMEINumber_F__c;

                        if(!woset.contains(worder.RecordType.DeveloperName))worder.Install_End_Datetime__c = System.now();

                       

                        Set<String> rtSet  = new Set<String>{
                            'TeachingTraining','Reagents','clinicalpromotion','InstrumentsTraining',
                            'calibration','MaintenanceOrder','ProblemSolving','InstallationOrder',
                            'TechnicalTours','ServiceOrder','UsersReflect','EvaluationTest','SoftwareInstallationTraining',
                            'Relocation','CalibrationEngineer','Upgrade'
                        };

                        if(rtSet.contains(worder.Case__r.RecordType.DeveloperName))worder.Install_End_Datetime__c = System.now();

                            
                            System.debug('====服务完成时间'+worder.Install_End_Datetime__c);
                       if( rtSet.contains(worder.Case__r.RecordType.DeveloperName)  
                            || worder.RecordType.DeveloperName =='ServiceOrder' || 
                                worder.RecordType.DeveloperName =='MaintenanceOrder' 
                            ){

                            if(worder.RecordType.DeveloperName != 'InstallationOrder')worder.Status__c  = '完成';

                        }else if(worder.RecordType.DeveloperName =='NonAgentInstallationOrder' || worder.RecordType.DeveloperName == 'InstallationOrder'){
                           
                            if(worder.IMEINumber__c != null)acase.IMEINumber__c = worder.IMEINumber__c;

                        }else{
                           
                             worder.Status__c = worder.ServiceTracking__c == null ? '处理中' :'完成';

                        }
                         //签名直接完成

                        acase.IsUpdateWorkOrder__c = !acase.IsUpdateWorkOrder__c ;
                       /* if(worder.RecordType.DeveloperName !='NonAgentInstallationOrder' 
                            && worder.RecordType.DeveloperName != 'InstallationOrder' && !woset.contains(worder.RecordType.DeveloperName))acase.Install_End_Datetime__c = System.now();
                        */
                        woset.remove('NonAgentInstallationOrder');
                        woset.remove('InstallationOrder');
                        if( woset.contains(worder.RecordType.DeveloperName)&& worder.RecordType.DeveloperName != 'InstallationOrder' )worder.Status__c = '完成';

                        SavePoint sp = Database.setSavepoint();
                        try {
                              at.ParentId = worder.Id;
                           // at.Name = worder.Account__r.Name + '_Sign.jpg';
                            if(btn.equals('UserDepartmen')){
                                at.Name = '使用科室负责人_Sign.jpg' ;
                            }/*else if(btn.equals('ManageDepartment')){
                                at.Name = '管理科室负责人_Sign.jpg';
                            }else if(btn.equals('EngineerSign')){
                                at.Name ='工程师_Sign.jpg';
                            }*/
                            
                           update acase;
                           update worder;
                           insert at; 
                            System.debug('+++'+worder);
                            User us = new User(Id = worder.Technician__c ,Status__c = '待命');
                            if(us.Id != null )update us;
                            isSuccess = true;
                            msg = '保存成功!';
                        }catch (Exception e){
                            isSuccess = false;
                            msg = e.getMessage()+e.getStackTraceString();
                            Database.rollback(sp);
                            //ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,e.getMessage()));

                            
                        }
                        

                       


                    }
                }

        
        
    }
}